package org.pjlib.common;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.json.JSONObject;
import org.pjlib.net.CallBack;
import org.pjlib.net.HttpUtils;
import org.pjlib.net.JSONUtils;
import org.pjlib.net.RequestCall;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * Created by ws on 2019/08/26.
 */
public class Updata {
    public static final int UpDataCode=1000;
    private static File file;

    public static void check(final Activity ctx, final boolean isToast, final boolean isBackDown) {
        HttpUtils.get(new RequestCall("api1_0_0/Index/version", 0), new CallBack() {
            @Override
            public void onResponseSuccess(RequestCall call) {
                JSONObject jo = JSONUtils.getJJson((JSONObject) call.getData(), "version");
                setData(ctx, jo, isToast,isBackDown);
            }
        });
    }
    private static void setSensitive(JSONObject jo){
        String sensitiveVersion=JSONUtils.getJStr(jo,"wyyImJinVersion");
        String sUrl=JSONUtils.getJStr(jo,"wyyImJinUrl");
        if(StringUtils.isEmpty(sUrl)){
            return;
        }
        String lastV=SPUtils.getInstance().getString("sensitiveVersion","");

        if(!lastV.equals(sensitiveVersion)){
            File lfile=new File(FileAccessor.IMESSAGE_FILE,String.format("sensitive%s.txt",lastV));
            if(lfile!=null){
                lfile.delete();
            }
            downSensitive(sensitiveVersion,sUrl);
        }else {
            File file=new File(FileAccessor.IMESSAGE_FILE,String.format("sensitive%s.txt",sensitiveVersion));
            if(file==null || !file.exists()){
                downSensitive(sensitiveVersion,sUrl);
            }else {
                try {
                    SensitiveWordUtil.init(new BufferedReader(new InputStreamReader(
                            new FileInputStream(file)
                            , StandardCharsets.UTF_8)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    private static void downSensitive(final String v, String url){
        OkGo.<File>get(url)
                .execute(new FileCallback(FileAccessor.IMESSAGE_FILE,String.format("sensitive%s.txt",v)) {
                    @Override
                    public void onSuccess(Response<File> response) {
                            SPUtils.getInstance().put("sensitiveVersion",v);
                       try {
                            SensitiveWordUtil.init(new BufferedReader(new InputStreamReader(
                                    new FileInputStream(response.body())
                                    , StandardCharsets.UTF_8)));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                });
    }
    private static void setData(final Activity ctx, JSONObject jo, boolean toast, final boolean isBackDown) {
        setSensitive(jo);
        final int version = JSONUtils.getJNum(jo, "androidVersion");
        if (!toast && version == SPUtils.getInstance().getInt("updataVersion")) {
            return;
        }
        if (version > AppUtils.getAppVersionCode()) {
            final String url = JSONUtils.getJStr(jo, "androidApkUrl");
            final boolean isNeedUpdata = JSONUtils.getJStr(jo, "androidQiangGeng").equals("1");
            new AlertDialog.Builder(ctx)
                    .setTitle("更新提示")
                    .setMessage(JSONUtils.getJStr(jo, "androidUpdataContent"))
                    .setSingleButton("立即更新", isNeedUpdata ? new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            updataApp(ctx, url, isNeedUpdata,isBackDown);
                        }
                    } : null)
                    .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            updataApp(ctx, url, isNeedUpdata, isBackDown);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SPUtils.getInstance().put("updataVersion", version);
                }
            })
                    .setCancelable(!isNeedUpdata)
                    .setCanceledOnTouchOutside(!isNeedUpdata)
                    .show();
        } else {
            if (toast) {
                ToastUtils.showShort("您已是最新版本！");
            }
        }
    }

    private static long currentSize;

    public static void updataApp(final Activity ctx, String url, final boolean isNeedUpdata, boolean isBackDown) {
        final UpdataDialog.Builder builder = new UpdataDialog.Builder(ctx)
                .setTitle("更新中")
                .setMessage("软件下载中，请稍后...");
        if (isNeedUpdata || !isBackDown) {
            builder.show();
        } else {
            ToastUtils.showShort("软件开始后台下载！");
        }
        OkGo.<File>get(url)
                .tag(ctx)
                .execute(new FileCallback() {
                    @Override
                    public void onStart(Request<File, ? extends Request> request) {
                        super.onStart(request);

                    }

                    @Override
                    public void onSuccess(Response<File> response) {
                        builder.dismiss();
                        if (response.body() == null || !response.body().exists()) {
                            error();
                        } else {
                            file = response.body();
                            checkOreo(ctx, response.body());
                        }
                    }

                    @Override
                    public void downloadProgress(Progress progress) {
                        if (progress.status == progress.LOADING && progress.currentSize > currentSize) {
                            currentSize = progress.currentSize;
                            builder.setProgress((int) (currentSize * 100 / progress.totalSize));
                        } else if (progress.status == progress.FINISH) {
                            builder.setTitle("下载完成").setMessage("开始更新软件");
                        }
                    }

                    private void error() {
                        if (!isNeedUpdata) {
                            builder.show();
                        }
                        builder.setTitle("更新失败").setMessage("更新错误，请稍后重试")
                                .setQuitBottom("退出", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                });
                    }

                    @Override
                    public void onError(Response<File> response) {
                        error();
                    }
                });
    }

    public static void install() {
        if (file != null) {
            AppUtils.installApp(file);
        }
    }

    public static void checkOreo(final Activity act, final File path) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0
            //判断是否可以直接安装
            boolean canInstall = act.getPackageManager().canRequestPackageInstalls();
            if (!canInstall) {
                new AlertDialog.Builder(act)
                        .setTitle("提示")
                        .setMessage("安装更新需要打开未知来源，是否打开？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + act.getPackageName()));
                                act.startActivityForResult(intent, UpDataCode);
                            }
                        }).show();
            } else {
                //安装APP
                AppUtils.installApp(path);
            }
        } else {
            //安装APP
            AppUtils.installApp(path);
        }
    }
}
